<template>
  <el-dialog center :title="title" :visible.sync="innerVisible">
    <div class="row">
      <div class="col-xs-12">
        <el-form ref="form" class="el-form-col" :model="model" label-width="106px" label-position="left">
          <el-row :gutter="15">
            <el-col :span="24">
              <el-form-item label="上级库位" prop="pId" :rules="[
                {required: true, message: '上级库位必须', trigger: 'change'}
              ]">
                <tree-select
                  :data="computedMenuData"
                  v-model="model.pId"
                >
                </tree-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="库位名称" prop="storageRegionName" :rules="[
                {required: true, message: '库位名称必须', trigger: 'change'}
              ]">
                <el-input v-model="model.storageRegionName" placeholder="库位名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
                已有绑定规则：
            </el-col>
            <el-col :span="6">
                所属类型
            </el-col>
            <el-col :span="6" class="text-center">
                =
            </el-col>
            <el-col :span="6">
                选择值
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in parentRulesArr" :key="index">
            <el-col :span="6">&nbsp;</el-col>
            <el-col :span="6">{{item.name}}</el-col>
            <el-col :span="6" class="text-center">=</el-col>
            <el-col :span="6">{{item.value}}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              新增绑定规则：
            </el-col>
            <el-col :span="6">
              所属类型
            </el-col>
            <el-col :span="6" class="text-center">
              =
            </el-col>
            <el-col :span="6">
              选择值
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              &nbsp;
            </el-col>
            <el-col :span="6">
              <el-form-item label="" prop="rules" label-width="0" :rules="[
                  {required: true, message: '规则必须', trigger: 'change'}
                ]">
                <el-select v-model="model.rules" filterable placeholder="请选择" @change="selectRule">
                  <el-option v-for="item in rulesArr"
                             :key="item.ruleKey"
                             :label="item.name"
                             :value="item.ruleKey">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="text-center">
              =
            </el-col>
            <el-col :span="6">
              <el-form-item v-if="!isAddress" label="" prop="subrules" label-width="0" :rules="[
                  {required: true, message: '规则必须', trigger: 'change'}
                ]">
                <el-select v-model="model.subrules" filterable placeholder="请选择" @change="selectSubrule">
                  <el-option v-for="item in subrulesArr"
                             :key="item.value"
                             :label="item.name"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <Cascade-address v-else ref="CascadeAddress" changeOnSelect v-model="model.subrules" @change="selectAddress" :level="3"></Cascade-address>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div style="width:100%; text-align: center">
        <el-button v-if="showButton" ref="makeSureButton" type="primary" size="medium" @click.prevent="makeSure" :loading="loading">{{id ? '保存' : '新增'}}</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import {dotData, arrayToTree, copy} from '@/utils'
import {selectRequired} from '@/utils/validate'
export default {
  name: 'storageModal',
  components: {
  },
  props: {
    objectId: {
      type: String,
      required: true
    },
    pId: {
      type: [String, Number],
      default: ''
    },
    menuData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      innerVisible: this.visible,
      loading: false,
      model: {
        id: '',
        pId: '',
        storageRegionName: '',
        objectId: '',
        type: '',
        rules: '',
        rulesName: '',
        subrules: '',
        subrulesName: ''
      },
      id: '',
      showButton: false,
      rulesArr: [],
      parentRulesArr: [],
      subrulesArr: [],
      isAddress: false
    }
  },
  computed: {
    title() {
      return this.id ? '编辑库位' : '新增库位'
    },
    computedMenuData() {
      return arrayToTree(copy(this.menuData, true), 'value', 'pid', 'children', '0', true) || []
    }
  },
  watch: {
    pId(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        this.model.pId = val
      }
    },
    'model.rules'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val !== 'address') {
        this.model.subrules = ''
        this.isAddress = false
        if (val) {
          this.getSubRules(val)
        }
      } else {
        this.model.subrules = []
        this.isAddress = true
      }
    },
    'model.pId'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        this.getRules()
        this.getParentRules()
      }
    }
  },
  created() {
  },
  methods: {
    selectRequired,
    getRules() {
      let id = ''
      if (this.model.pId === '0' || this.model.pId === 0) {
        id = ''
      } else {
        id = this.model.pId
      }
      this.$ajax.get('/ms-warehouse-order/sorting-maintenance/query-rules', {regionId: id}).then(response => {
        this.rulesArr = dotData(response, 'data')
      })
    },
    getParentRules() {
      if (this.model.pId === '0' || this.model.pId === 0) {
        this.parentRulesArr = []
        return
      }
      this.$ajax.get('/ms-warehouse-order/sorting-maintenance/query-chain-values', {regionId: this.model.pId}).then(response => {
        this.parentRulesArr = dotData(response, 'data')
      })
    },
    getSubRules(rules) {
      if (rules) {
        this.$ajax.get('/ms-warehouse-order/sorting/query-sql-values', {id: rules}).then(response => {
          this.subrulesArr = dotData(response, 'data')
        })
      }
    },
    selectRule(vId) {
      let obj = {}
      obj = this.rulesArr.find((item) => {
        return item.ruleKey === vId
      })
      this.model.rulesName = obj.name
      this.model.subrules = ''
    },
    selectSubrule(vId) {
      let obj = {}
      obj = this.subrulesArr.find((item) => {
        return item.value === vId
      })
      this.model.subrulesName = obj.name
    },
    selectAddress(val) {
      let addressArr = []
      val.forEach(v => {
        addressArr.push(v.text)
      })
      this.model.subrulesName = addressArr.join(',')
    },
    makeSure() {
      this.$refs.form.validate().then(result => {
        if (result === false) {
          return
        }
        this.loading = true
        /* 暂无修改 以及删除
        let data = copy(this.model, true)
        if (this.id) {
          data.operation = 'update'
        } else {
          data.operation = 'insert'
        }
        if (data.pId === '0') {
          data.type = 'warehouse'
        } else {
          data.type = 'default'
        }
        data.objectId = this.objectId
        httpSuccessPost('/ms-warehouse-order/ch-warehouse-manager/operateRegion', data).then(response => {
        */
        let data = {
          pid: this.model.pId,
          name: this.model.storageRegionName,
          warehouseId: this.objectId,
          sortingRules: [{
            key: this.model.rules,
            value: this.model.subrules,
            valueName: this.model.subrulesName
          }]
        }
        this.$ajax.post('/ms-warehouse-order/sorting-maintenance/save-region-rule', data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.loading = false
            this.$confirm('操作成功', '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.$emit('refresh', true)
              this.loading = false
              this.innerVisible = false
            })
          } else {
            this.loading = false
          }
        })
      })
    },
    show(id) {
      this.showButton = true
      this.visible = true
      if (id) {
        this.id = id
        this.$ajax.get('/ms-warehouse-order/ch-warehouse-manager/getStorageRegionInfo', {id: id}).then(response => {
          this.model.id = id
          this.model.storageRegionName = dotData(response.data, 'storageRegionName')
          this.model.pId = dotData(response.data, 'pId')
          this.model.objectId = dotData(response.data, 'objectId')
        })
      } else {
        // 新增
        this.id = ''
        this.model.id = ''
        this.model.storageRegionName = ''
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      }
      this.$nextTick(_ => {
        this.model.pId = this.pId
        setTimeout(_ => {
          this.innerVisible = true
        }, 100)
      })
    }
  }
}
</script>
